const domain ="https://weiqun.qiyedaishu.com";
//const domain = "http://localhost:19829";
const md5 = require("md5.js");
const app = getApp();
const FormatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(FormatNumber).join('/') + ' ' + [hour, minute, second].map(FormatNumber).join(':')
}

const FormatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
String.prototype.RHtml = function () {
  return this.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, "");
};

String.prototype.ReplaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

Array.prototype.Remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

Array.prototype.RemoveAt = function (n) {
  if (n < 0)
  { return this; }
  else
  { return this.slice(0, n).concat(this.slice(n + 1, this.length)); }
};

Array.prototype.indexOf = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) return i;
  }
  return -1;
};

Array.prototype.Max = function () {
  return Math.max.apply(Math, this);
};

Array.prototype.Min = function () {
  return Math.min.apply(Math, this);
};

String.prototype.ToDate = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("MM.dd");
};

Date.prototype.Format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month 
    "d+": this.getDate(), //day 
    "h+": this.getHours(), //hour 
    "m+": this.getMinutes(), //minute 
    "s+": this.getSeconds(), //second 
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
    "S": this.getMilliseconds() //millisecond 
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

function Ajax(data, callback) {
  data.Timestamp = new Date().getTime();
  data.OpenID = app.User.OpenID;
  data.Token = wx.getStorageSync('token') || '';
  data.Sign = md5.GetSign(data);
  wx.request({
    url: domain + '/tools/API.ashx',
    data: data,
    dataType:'json',
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      wx.hideLoading();
      //如果登录token失效，则重新登录
      if (res.data.msg =="token失效，请重新登录"){
        wx.setStorageSync("token", "");
        Login(function (res){
          Ajax(data, function(res){
            if(callback) {
              callback(res)
            }
          });
        });
      }else{
        if (callback) {
          callback(res.data)
        }
      }
    },
    fail: function (res) {
      wx.hideLoading();
      Error("网络已经中断");
    }
  })
};
function Upload(path, data, callback){
  wx.uploadFile({
    url: domain + '/tools/Upload.ashx',
    filePath: path,
    name: 'img',
    formData: data,
    success: function (res) {
      if (callback) {
        callback(res.data)
      }
    }
  });
}
function Error(title) {
  wx.showToast({
    title: title,
    image: '/image/error.png'
  });
};
function Success(title, callback) {
  wx.showToast({
    title: title,
    success: function () {
      if (callback) { 
        setTimeout(function(){
          callback(); 
        },1000);
      }
    }
  });
};
function Loading(title) {
  wx.showLoading({ 
    title: title
  });
};
function Confirm(title, callback) {
  wx.showModal({
    title: '提示',
    content: title,
    success: function (res) {
      if (res.confirm && callback) {
        callback();
      }
    }
  });
};
function Login(fun) {
  var that = this;
  var token = wx.getStorageSync('token') || '';
  //token = ''; wx.setStorageSync("token", ""); //如果需要，可以清除用户信息
  if (token == '') {
    wx.getUserInfo({
      success: function (user) {
        wx.login({
          success: function (res) {
            if (res.code) {
              var data = {};
              data.code = res.code;
              data.realname = user.userInfo.nickName;
              data.headimg = user.userInfo.avatarUrl;
              data.sex = user.userInfo.gender;
              data.province = user.userInfo.province;
              data.city = user.userInfo.city;
              data.act = "Login_Xcx";
              Ajax(data, function (json) {
                wx.setStorageSync("token", json.data.Token);
                app.User = json.data;
                if (fun) { fun(json); }
              });
            } else {
              Success('获取用户登录态失败！');
            }
          }
        });
      }
    });
  } else {
    var data = {};
    data.act = "Login_Xcx";
    data.token = token;
    Ajax(data, function (json) {
      wx.setStorageSync("token", json.data.Token);
      app.User = json.data;
      if (fun) { fun(json); }
    });
  }
};
module.exports = {
  Domain:domain,
  FormatTime: FormatTime,
  Ajax:Ajax,
  Upload:Upload,
  Login: Login,
  Success: Success,
  Error:Error,
  Loading: Loading,
  Confirm: Confirm
}
